<?php

namespace Tools\Utils;

class Sql
{
    /**
     * sql 参数过滤
     * @param string $str
     * @return mixed
     */
    public static function sql_filter(string $str)
    {
        $filter = ['select ', 'insert ', 'update ', 'delete ', 'drop', 'truncate ', 'declare', 'xp_cmdshell', '/add', ' or ', 'exec', 'create', 'chr', 'mid', ' and ', 'execute'];
        $toupper = array_map(function ($str) {
            return strtoupper($str);
        }, $filter);
        return str_replace(array_merge($filter, $toupper, ['%20']), '', $str);
    }

    /**
     *对数据库数据排序
     * @param $data array 需要排序的数据，形如：[['id'=>1, 'score'=>3],...]
     * @param $orderby string 排序规则，形如："id desc, score asc"
     * @author yqp
     *
     */
    function sort_with_orderby(array &$data, $orderby = '')
    {
        if (empty($orderby)) {
            return TRUE;
        }
        $sort = ['asc' => SORT_ASC, 'desc' => SORT_DESC];
        $order = explode(',', $orderby);
        array_walk($order, function (&$item, $key) {
            $item = explode(' ', trim(preg_replace('/\s+/', ' ', $item)));
        });
        $params = [];
        foreach ($order as $value) {
            $arr = array_column($data, $value[0]);
            if (empty($arr)) {
                continue;
            }
            $params[] = $arr;
            $params[] = isset($value[1]) ? $sort[strtolower($value[1])] : $sort['asc'];
            unset($arr);
        }
        $params[] = &$data;

        return call_user_func_array('array_multisort', $params);
    }

    /**
     * 根据$id获取对应表序号，提出方法是方便变更
     * @param $id
     * @return string
     */
    function gettablenum($tablename, $id)
    {
        return $tablename . "_" . str_pad(floor($id / 50000), 4, "0", STR_PAD_LEFT);
    }

}
